package com.ywq.wechatordersys.service.impl;

import com.ywq.wechatordersys.constant.ErrorCode;
import com.ywq.wechatordersys.data.OrderDetail;
import com.ywq.wechatordersys.data.OrderMaster;
import com.ywq.wechatordersys.data.ProductInfo;
import com.ywq.wechatordersys.dto.CartDTO;
import com.ywq.wechatordersys.dto.OrderDTO;
import com.ywq.wechatordersys.enums.OrderStatus;
import com.ywq.wechatordersys.enums.PayStatus;
import com.ywq.wechatordersys.exception.MyException;
import com.ywq.wechatordersys.repository.OrderDetailRepository;
import com.ywq.wechatordersys.repository.OrderMasterRepository;
import com.ywq.wechatordersys.service.OrderService;
import com.ywq.wechatordersys.service.ProductInfoService;
import com.ywq.wechatordersys.utils.IDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.beans.Transient;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;

    /**
     * 创建订单
     *
     * @param orderDTO
     */
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {

        long l = System.currentTimeMillis();

        ArrayList<CartDTO> cartDTOS = new ArrayList<>();

        //1.生成订单id
        String orderId = IDUtils.createID();
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderId(orderId);
        //1.查询商品的数量 价格

        //1.1创建一个变量 记录商品总价
        BigDecimal totalAmout = BigDecimal.ZERO;
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            //获取商品的id
            String productId = orderDetail.getProductId();
            ProductInfo product = productInfoService.getProduct(productId);
            if (product == null) {
                throw new MyException(ErrorCode.PRODUCT_NOT_FOUND, "product is not found,please check product id");
            }

            //检测库存
            Integer productStock = product.getProductStock();
            //购买的商品的数量
            Integer productQuantity = orderDetail.getProductQuantity();

            if (productStock < productQuantity) {
                throw new MyException(ErrorCode.PRODUCT_NO_STOCK, "商品" + productId + "库存不足");
            }

            //获取到了商品的单价
            BigDecimal productPrice = product.getProductPrice();

            //单个商品购买的价格 数量*单价
            BigDecimal i = productPrice.multiply(new BigDecimal(productQuantity));
            //2.计算总价
            totalAmout = totalAmout.add(i);

            //添加商品详情到数据库
            orderDetail.setOrderId(orderId);
            //生成订单详情的id
            String id = IDUtils.createID();
            orderDetail.setOrderDetailId(id);
            //设置商品的价格
            BeanUtils.copyProperties(product, orderDetail);
            //订单详情写入数据库
            orderDetailRepository.save(orderDetail);
            cartDTOS.add(new CartDTO(productId, productQuantity));
        }

        //订单主表写入

        orderMaster.setOrderAmount(totalAmout);
        orderMaster.setOrderName(orderDetailList.get(0).getProductName());
        orderMaster.setPayStatus(OrderStatus.NEW.getCode());
        orderMaster.setOrderStatus(PayStatus.WAIT.getCode());

        orderMasterRepository.save(orderMaster);
        //4.扣库存
        productInfoService.minStock(cartDTOS);
        BeanUtils.copyProperties(orderMaster, orderDTO);


        long l2 = System.currentTimeMillis();
        System.out.println("计算方法的耗时:" + (l2 - l));
        System.out.println(orderDTO.toString());
        return orderDTO;
    }


    /**
     * 查询单个订单
     *
     * @param orderId
     */
    @Override
    public OrderDTO findOne(String orderId) {
        //查询出来主订单
        Optional<OrderMaster> byId = orderMasterRepository.findById(orderId);
        OrderMaster orderMaster = byId.get();
        if (orderMaster == null) {
            throw new MyException(ErrorCode.ORDER_NOT_FOUND, "订单不存在");
        }

        //根据主订单id查询详情订单
        List<OrderDetail> orderDetails = orderDetailRepository.findByOrderId(orderId);
        if (orderDetails == null
                || orderDetails.isEmpty()) {
            throw new MyException(ErrorCode.ORDER_DETAIL_NOT_FOUND, "订单详情异常");

        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetails);
        return orderDTO;
    }

    /**
     * 查询订单列表
     * *
     *
     * @param buyerOpenid
     * @param pageable
     */
    @Override
    public List<OrderDTO> findList(String buyerOpenid, Pageable pageable) {

        ArrayList<OrderDTO> orderDTOS = new ArrayList<>();
        Page<OrderMaster> byBuyerOpenid = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderMaster> content = byBuyerOpenid.getContent();


        for (OrderMaster orderMaster : content) {
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderMaster, orderDTO);
            List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderMaster.getOrderId());


            orderDTO.setOrderDetailList(orderDetailList);

            orderDTOS.add(orderDTO);
        }


        return orderDTOS;
    }

    /**
     * 取消订单
     *
     * @param  orderDTO
     */
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        //首先判断订单的状态
        String orderId = orderDTO.getOrderId();
        OrderDTO orderDTO1 = findOne(orderId);
        if (orderDTO1.getOrderStatus().equals(OrderStatus.NEW.getCode())) {
            //新建的订单可以取消 其他的两种状态是已取消和已完结
            //修改订单的状态
            OrderMaster orderMaster = new OrderMaster();
            orderDTO1.setOrderStatus(OrderStatus.CANCEL.getCode());
            BeanUtils.copyProperties(orderDTO1, orderMaster);


            //保存    //修改状态
            OrderMaster save = orderMasterRepository.save(orderMaster);
            if(save==null ||    !save.getOrderStatus().equals(OrderStatus.CANCEL.getCode())){
                throw  new MyException(ErrorCode.ORDER_STATUS_EXCEPTION,"订单状态修改失败");
            }


        }



        List<OrderDetail> orderDetailList = orderDTO1.getOrderDetailList();

        if(CollectionUtils.isEmpty(orderDetailList)){
            throw  new MyException(106,"订单是空的");
        }


        ArrayList<CartDTO> cartDTOS = new ArrayList<>();


        for (OrderDetail orderDetail : orderDetailList) {

            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity());
            cartDTOS.add(cartDTO);
        }
        //修改商品的库存
        productInfoService.addStock(cartDTOS);
        //退款(如果已经支付)
        if (orderDTO1.getPayStatus().equals(PayStatus.SUCCESS.getCode())) {
            //    需要退款
// TODO: 2018/4/17  退款
        }

        return orderDTO1;
    }

    /**
     * 完结订单
     *
     * @param orderDTO
     */
    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        //首先判断订单的状态
        String orderId = orderDTO.getOrderId();
        OrderDTO orderDTO1 = findOne(orderId);
        if (orderDTO1.getOrderStatus().equals(OrderStatus.FINISH.getCode()) ||
                orderDTO1.getOrderStatus().equals(OrderStatus.CANCEL.getCode())) {
            throw new MyException(ErrorCode.ORDER_STATUS_EXCEPTION, "订单状态异常");
        }

        //修改订单的状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO1.setOrderStatus(OrderStatus.FINISH.getCode());
        BeanUtils.copyProperties(orderDTO1, orderMaster);
        //保存
        OrderMaster save = orderMasterRepository.save(orderMaster);
        if (save==null){

            throw new MyException(ErrorCode.ORDER_STATUS_EXCEPTION,"订单状态更新失败了");
        }
        return orderDTO1;
    }

    /**
     * 支付订单
     *
     * @param orderDTO
     */
    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {

 //获取订单的id
        String orderId = orderDTO.getOrderId();
//查询订单
        OrderDTO one = findOne(orderId);

        //首先获取订单的状态
        Integer orderStatus = one.getOrderStatus();
        //只有新建的订单可以支付 取消和完结的订单不能支付

        if (!orderStatus.equals(OrderStatus.NEW.getCode())){
            throw new MyException(ErrorCode.ORDER_STATUS_EXCEPTION,"订单状态异常");
        }
        //获取订单的支付状态  只有未支付的可以支付
        Integer payStatus = one.getPayStatus();
        if (!payStatus.equals(PayStatus.WAIT.getCode())){
            throw new MyException(ErrorCode.ORDER_STATUS_EXCEPTION,"订单状态异常");
        }

        OrderMaster orderMaster = new OrderMaster();
//设置状态为支付状态
        one.setPayStatus(PayStatus.SUCCESS.getCode());
        //保存
        BeanUtils.copyProperties(one,orderMaster);

        OrderMaster save = orderMasterRepository.save(orderMaster);
        if (save==null){
            throw new MyException(ErrorCode.ORDER_STATUS_EXCEPTION,"订单状态异常");
        }
        return one;
    }
}
